import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { Md5 } from "ts-md5/dist/md5";
import { UserInfoProvider, user_info } from '../../providers/user-info/user-info';
import { NavParams } from 'ionic-angular/navigation/nav-params';


/**
 * Generated class for the RegisterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-register',
	templateUrl: 'register.html',
})
export class RegisterPage {

	eyeshow = true;
	member_id: any;
	userInfo: user_info = new user_info();
	veritycode = '';
	sendStatus:any;

	/*模型设置*/
	public registerInfo = {
		UserName: '',
		PassWord: '',
		Nickname: ''
	};

	//短信倒计时
	date = 0;

	public Coupons = [
		{
			//   expiry_date:null,//券有效期
			//   denomination:null,//代金券面额
			ma_coupon: { coupon_name: null,//优惠券名称
				         give_num: 1}, 

		}

	]
	constructor(
		public navCtrl: NavController,
		public navParams: NavParams,
		public viewCtrl: ViewController,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public user: UserInfoProvider) {
			this.sendStatus = navParams.get('sendStatus');
		 }

	ionViewDidLoad() {
		console.log('ionViewDidLoad RegisterPage');
	}
	// 页面跳转的方式
	useragr() {
		this.navCtrl.push('UserAgreementPage');
	}
	/**
	 * 用户注册
	 */
	registerSuccess() {
		/*2018手机号正则表达式  /^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/
		"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。 
		*/
		var subscriber = /^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/;
		var silly = subscriber.test(this.registerInfo.UserName);
		if (this.registerInfo.UserName == '' || this.registerInfo.UserName == null) {
			this.dialog.showAlert('请输入手机号码', '');
			return;
		}
		if (this.registerInfo.UserName.length != 11) {
			this.dialog.showAlert('请输入11位手机号码', '');
			return;
		}
		if (!silly) {
			this.dialog.showAlert('手机号不合法', '');
			return;
		}
		if (this.registerInfo.PassWord == '' || this.registerInfo.PassWord == null) {
			this.dialog.showAlert('请输入密码', '');
			return;
		}
		if (this.registerInfo.PassWord.length < 6 || this.registerInfo.PassWord.length > 16) {
			this.dialog.showAlert('密码必须6-16位', '');
			return;
		}
		// if(this.registerInfo.PassWord.length!=6) {
		// 	this.dialog.showAlert('密码只能6位','');
		// 	return;
		// }
		// else if(this.registerInfo.Nickname==''||this.registerInfo.Nickname==null) {
		// 	this.dialog.showAlert('请输入昵称','');
		// 	return;
		// }
		var params = {
			username: this.registerInfo.UserName,
			password: this.registerInfo.PassWord,
			nickname: this.registerInfo.Nickname,
		};
		this.http.postJson('', 'users/member/registers', {
			'phone': params.username,
			'password': Md5.hashStr(params.password).toString(),
			//'password': params.password,不是Md5加密格式写法
			'nickname': params.nickname,
			'vcode': this.veritycode,
			"balance": "0.00",
			"local_balance": "0.00",
			"member_state": "1",
		}, '').then(res => {
			if (res['status'] == 200) {
				this.dialog.showAlert('注册成功!', '').then((res) => {
					this.login();
				});

				//this.navCtrl.push('LoginPage');
			} else {
				this.dialog.showAlert(res['message'], '');
			}

		});
	}

	async login() {
		const res = await this.http.postJson('', 'users/member/login', { 'phone': this.registerInfo.UserName, 'password': this.registerInfo.PassWord }, '')
			.then(res => {
				if (res['status'] == 200) {
					//this.dialog.showAlert('您好'+res['data']['nickname'], res['message']);		
					res['data']['password'] = this.registerInfo.PassWord;
					this.member_id = res['data']['member_id'];
					// this.storage.saveStorage("login_info", res['data']);
					res['data']['isAutomaticLogon'] = false;
					this.userInfo = res['data'];
					this.user.setuserInfo(this.userInfo);
					this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
					this.getdictionary();
					this.getCoupons().then(res => {
						if (this.Coupons.length > 0) {
							if(this.Coupons[0].ma_coupon.give_num >1){ 
								this.dialog.showAlert('新用户注册享受' + this.Coupons[0].ma_coupon.give_num + '张' + this.Coupons[0].ma_coupon.coupon_name, '');
							}else{ 
								this.dialog.showAlert('新用户注册享受' + this.Coupons[0].ma_coupon.coupon_name + '优惠', '');
							}													
						}
						this.navCtrl.push('TabsPage');
					});

				} else {
					this.dialog.showToast(res['message'], '');
				}
			});
	}

	getdictionary() {
		this.http.postJson('', 'aindex/dictionary/index',
			{
				select: "m.D_GROUP",
				joinWith: "group", "groupby": "D_GROUP", "indexBy": "D_GROUP", "limit": 0,
				where: ["<>", "s_dictionary.D_STATE", 0]
			}, '')
			.then(res => {
				if (res['status'] == 200) {
					this.storage.saveStorage("dictionary", JSON.stringify(res['data']));
				}
			});
	}


	async getCoupons() {
		let a = await this.http.postJson('', 'member/memberco/index?page=1', {
			"where": ["=", "member_id", this.member_id],
			"limit": 15,
			"joinwith": ["ma_coupon"]
		}, '');

		console.log(a)
		if (a['status'] == 200) {
			console.log(a)
			this.Coupons = a['data'];
			// this.getMessage(res['data']);
		}
		return;
	}

	getSMS() {
		var subscriber = /^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/;
		var silly = subscriber.test(this.registerInfo.UserName);
		if (this.registerInfo.UserName == '' || this.registerInfo.UserName == null) {
			this.dialog.showAlert('请输入手机号码', '');
			return;
		}
		if (this.registerInfo.UserName.length != 11) {
			this.dialog.showAlert('请输入11位手机号码', '');
			return;
		}
		if (!silly) {
			this.dialog.showAlert('手机号不合法', '');
			return;
		}
		this.http.postJson('', 'users/member/sms',
			{
				mobiles: this.registerInfo.UserName,
				type: "register",
				sendStatus:this.sendStatus,
				send_from: 3
			}, '')
			.then(res => {
				let form = this;
				if (res['status'] === 200) {
					this.date = 60;
					const interval = setInterval(function () {
						form.date--;
						if (form.date === 0) { clearInterval(interval); }
					}, 1000);

				}else if(res['status'] == 500 && res['code']==2){
					this.dialog.showAlert(res['message'], '').then((res) => {
						this.navCtrl.push('LoginPage');
					});
				}else if (res['status'] === 500) {
					this.dialog.showAlert(res['message'], '');
				}
			});
	}


	// getverity(){
	// 	var params = {
	// 		phone: this.registerInfo.UserName,
	// 	};
	// 	this.http.postJson('', 'users/member/sms', {
	// 		'phone': params.phone,
	// 		},'').then(res => {
	// 		if(res['status'] == 200) {
	// 			this.dialog.showAlert('提示',res['message']);
	// 		} else {
	// 			this.dialog.showAlert('提示', res['message']);
	// 		}
	// 	});

	// }

	// ///验证码倒计时
	// public verifyCode: any = {
	// 	verifyCodeTips: "获取验证码",
	// 	countdown: 120, //总共时间
	// 	disable: true
	// };

	// //倒计时
	// settime() {
	// 	if(this.verifyCode.countdown == 0) {
	// 		debugger
	// 		this.verifyCode.verifyCodeTips = "获取验证码";
	// 		this.verifyCode.disable = true;
	// 		return;
	// 	} else {
	// 		this.verifyCode.countdown--;
	// 	}
	// 	setTimeout(() => {
	// 		this.verifyCode.verifyCodeTips = "重新获取" + this.verifyCode.countdown + "秒";
	// 		this.settime();
	// 	}, 1000);
	// }

}

